#include "operation.h"
#include "led.h"
#include "sensor.h"
#include "servo.h"
#include <stdio.h>
#include <string.h>

#include "ESP8266.h"

static const char *MQTT_FORMAT = "+MQTTSUBRECV:%*d,\"" SUBSCRIBE_TOPIC "\",%*d,%49[^:]:%49s";

// 解析MQTT消息字符串
bool parse_mqtt_message(MessageKeyValue *kvp, const char *message)
{
    int ret = sscanf(message, MQTT_FORMAT, kvp->key, kvp->value);
    if (ret == 2)
    {
        return true;
    }
    return false;
}

// 窗户的操作处理数组 - 定义了窗户支持的操作及其处理函数
OperationHandler door_operations[] = {
    {"open", door_open},
    {"close", door_close}};

OperationHandler light_operations[] = {
    {"on", turn_on_light},
    {"off", turn_off_light}};

OperationHandler environment_operations[] = {
    {"get", Get_environment}};

// 实体处理数组 - 存储系统支持的所有实体及其操作
EntityHandler entity_handlers[] = {
    {"door", door_operations, sizeof(door_operations) / sizeof(door_operations[0])},
    {"env", environment_operations, sizeof(environment_operations) / sizeof(environment_operations[0])},
    {"light", light_operations, sizeof(light_operations) / sizeof(light_operations[0])}};

/**
 * 处理消息的核心函数
 * 根据消息中的实体和操作类型，调用对应的处理函数
 * @param msg 包含实体和操作信息的消息结构
 * @return 如果找到并执行了对应操作，返回操作结果；否则返回false
 */
bool handle_message(const MessageKeyValue *msg)
{
    size_t num_entities = sizeof(entity_handlers) / sizeof(entity_handlers[0]);

    // 遍历所有支持的实体
    for (size_t i = 0; i < num_entities; i++)
    {
        // 找到匹配的实体
        if (strcmp(msg->key, entity_handlers[i].entity) == 0)
        {
            // 遍历该实体支持的所有操作
            for (size_t j = 0; j < entity_handlers[i].num_operations; j++)
            {
                // 找到匹配的操作
                if (strcmp(msg->value, entity_handlers[i].operations[j].operation) == 0)
                {
                    // 执行对应的操作函数并返回结果
                    return entity_handlers[i].operations[j].action();
                }
            }
        }
    }

    // 未找到匹配的实体或操作
    return false;
}
